/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.suli.wcs.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.entity.Result;
import me.zhengjie.suli.check.domain.CheckRecord;
import me.zhengjie.suli.check.repository.CheckRecordRepository;
import me.zhengjie.suli.inventory.domain.Inventory;
import me.zhengjie.suli.inventory.repository.InventoryRepository;
import me.zhengjie.suli.inventory.repository.TallyTasksRepository;
import me.zhengjie.suli.inventory.service.InventoryService;
import me.zhengjie.suli.inventory.service.impl.InventoryServiceImpl;
import me.zhengjie.suli.location.domain.Location;
import me.zhengjie.suli.location.repository.LocationRepository;
import me.zhengjie.suli.outHouse.domain.OrderDetail;
import me.zhengjie.suli.outHouse.domain.Orders;
import me.zhengjie.suli.outHouse.repository.OrderDetailRepository;
import me.zhengjie.suli.outHouse.repository.OrdersRepository;
import me.zhengjie.suli.tasks.domain.TaskDetail;
import me.zhengjie.suli.tasks.domain.Tasks;
import me.zhengjie.suli.tasks.repository.TaskDetailRepository;
import me.zhengjie.suli.tasks.repository.TasksRepository;
import me.zhengjie.suli.toHouse.domain.Receipt;
import me.zhengjie.suli.toHouse.domain.ReceiptDetail;
import me.zhengjie.suli.toHouse.repository.ReceiptDetailRepository;
import me.zhengjie.suli.toHouse.repository.ReceiptRepository;
import me.zhengjie.suli.toHouse.service.ReceiptService;
import me.zhengjie.suli.toHouse.service.impl.ReceiptServiceImpl;
import me.zhengjie.suli.wcs.domain.AgvTaskDetail;
import me.zhengjie.suli.wcs.domain.AgvTasks;
import me.zhengjie.suli.wcs.repository.AgvTaskDetailRepository;
import me.zhengjie.suli.wcs.repository.AgvTasksRepository;
import me.zhengjie.suli.wcs.service.AgvTasksService;
import me.zhengjie.suli.wcs.service.dto.*;
import me.zhengjie.suli.wcs.service.mapstruct.AgvTasksMapper;
import me.zhengjie.util.CommonUtil;
import me.zhengjie.util.UuidUtil;
import me.zhengjie.utils.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLOutput;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Allen Gao
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2024-02-04
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class AgvTasksServiceImpl implements AgvTasksService {
    private final CheckRecordRepository checkRecordRepository;
    private final ReceiptRepository receiptRepository;
    private final ReceiptDetailRepository receiptDetailRepository;
    private final TasksRepository tasksRepository;
    private final AgvTaskDetailRepository agvTaskDetailRepository;
    private final LocationRepository locationRepository;

    private final AgvTasksRepository agvTasksRepository;
    private final AgvTasksMapper agvTasksMapper;
    private final InventoryRepository inventoryRepository;
    private final OrdersRepository ordersRepository;
    private final OrderDetailRepository orderDetailRepository;
    private final CommonUtil commonUtil;
    private final TaskDetailRepository taskDetailRepository;
    private final InventoryService inventoryService;
    private final TallyTasksRepository tallyTasksRepository;

    public static boolean flag = false;

    @Value("${sccs.port}")
    private String sccsPort;

    @Value("${sccs.ip}")
    private String sccsIp;

    @Value("${agv.ip}")
    private String agvIp;

    @Value("${agv.port}")
    private String agvPort;

    @Override
    public Map<String, Object> queryAll(AgvTasksQueryCriteria criteria, Pageable pageable) {
        Page<AgvTasks> page = agvTasksRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(agvTasksMapper::toDto));
    }

    @Override
    public List<AgvTasksDto> queryAll(AgvTasksQueryCriteria criteria) {
        return agvTasksMapper.toDto(agvTasksRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public AgvTasksDto findById(String id) {
        AgvTasks agvTasks = agvTasksRepository.findById(id).orElseGet(AgvTasks::new);
        ValidationUtil.isNull(agvTasks.getId(), "AgvTasks", "id", id);
        return agvTasksMapper.toDto(agvTasks);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AgvTasksDto create(AgvTasks resources) {
        return agvTasksMapper.toDto(agvTasksRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AgvTasks resources) {
        AgvTasks agvTasks = agvTasksRepository.findById(resources.getId()).orElseGet(AgvTasks::new);
        ValidationUtil.isNull(agvTasks.getId(), "AgvTasks", "id", resources.getId());
        agvTasks.copy(resources);
        agvTasksRepository.save(agvTasks);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            agvTasksRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<AgvTasksDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AgvTasksDto agvTasks : all) {
            Map<String, Object> map = new LinkedHashMap<>();
//            map.put("任务号", agvTasks.getTaskCode());
//            map.put("任务单据号", agvTasks.getBillNumber());
//            map.put("父订单号", agvTasks.getParrentOrderId());
//            map.put("小车类型", agvTasks.getCarrierType());
//            map.put("任务类型", agvTasks.getType());
//            map.put("优先级", agvTasks.getPriority());
//            map.put("任务点列表", agvTasks.getPosArr());
//            map.put("点位列表的数量", agvTasks.getPosArrLength());
//            map.put("附加协议", agvTasks.getOtherOrderData());
//            map.put("实例化时间", agvTasks.getCallTime());
//            map.put("创建用户", agvTasks.getCreateBy());
//            map.put("修改用户", agvTasks.getUpdateBy());
//            map.put("创建日期", agvTasks.getCreateTime());
//            map.put("修改日期", agvTasks.getUpdateTime());
//            map.put("任务状态", agvTasks.getStatus());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public String sendToAgv(String param) {
//        List<String> ids = JSON.parseArray(param , String.class);
//        List<Orders> allById = ordersRepository.findAllById(ids);
//        List<JSONObject> task = new ArrayList<>();
//        List<String> numberNotEnough = new ArrayList<>();
//        for (Orders orders : allById) {
//            List<Inventory> byMaterialCode = inventoryRepository.findByMaterialCode(orders.getMaterialCode());
//            List<Inventory> collect = byMaterialCode.stream().sorted(Comparator.comparing(Inventory::getCreateTime)).collect(Collectors.toList());
//            BigDecimal i = new BigDecimal(0);
//            for (Inventory inventory : collect) {
//                i = i.add(inventory.getMaterialNumber());
//                JSONObject jsonObject = new JSONObject();
//                jsonObject.put("toLocationCode" , inventory.getLocationCode());
//                task.add(jsonObject);
//                String location = inventory.getLocationCode().toString();
//                if (location.substring(location.length()-2).equals("_2")){
//                    String str = location.substring(0 , location.length()-1);
//                    List<Inventory> byLocationCode = inventoryRepository.findByLocationCode(str + "1" );
//                    if (null != byLocationCode || !byLocationCode.isEmpty()){
//                        JSONObject relocation = new JSONObject();
//                        relocation.put("toLocationCode" , inventory.getLocationCode());
//                        task.add(jsonObject);
//                    }
//                }
//                if (i.compareTo(orders.getPlanQty()) >= 0){
//                    break;
//                }
//            }
//            if(i.compareTo(orders.getPlanQty()) < 0){
//                numberNotEnough.add(orders.getOrderCode());
//            }
//        }
//        JSONObject o = new JSONObject();
//        o.put("taskType" , "carry");
//        o.put("groupPriority" , "carry");
//        o.put("taskDescribe" , task);
//        commonUtil.httpPost("http://localhost:8000" , o);

        return null;
    }

    @Override
    public String trayCodeReturn(String trayCode) {
        Tasks byTrayCode = tasksRepository.findByTrayCode(trayCode).stream().findFirst().orElse(null);
        String taskId = UuidUtil.genCode();
        Tasks tasks = new Tasks();
        tasks.setStatus(1);
        tasks.setId(taskId);
        AgvSendTask agvSendTask = new AgvSendTask();
        agvSendTask.setTaskType("putaway");
        AgvSendTasks agvSendTasks = new AgvSendTasks();
        agvSendTasks.setTaskCode(taskId);
        AgvSendTaskDescribe agvSendTaskDescribe = new AgvSendTaskDescribe();
        agvSendTaskDescribe.setToLocationCode(byTrayCode.getLocationFrom());
        agvSendTaskDescribe.setFromLocationCode("CY02");
        agvSendTasks.setAgvSendTaskDescribe(agvSendTaskDescribe);
        List<AgvSendTasks> agvSendTasksList = new ArrayList<>();
        agvSendTasksList.add(agvSendTasks);
        agvSendTask.setTasks(agvSendTasksList);
        tasks.setLocationTo(byTrayCode.getLocationFrom());
        tasks.setLocationFrom("CY02");
        tasks.setStartTime(new Timestamp(new Date().getTime()));
        AgvTasks agvTasks = new AgvTasks();
        agvTasks.setId(UuidUtil.genCode());
        agvTasks.setTaskType("putaway");
        agvTasks.setStatus(1);
        AgvTaskDetail agvTaskDetail = new AgvTaskDetail();
        agvTaskDetail.setId(UuidUtil.genCode());
        agvTaskDetail.setMainId(agvTasks.getId());
        agvTaskDetail.setTaskCode(UuidUtil.genCode());
        agvTaskDetail.setToLocationCode(byTrayCode.getLocationFrom());
        agvTaskDetail.setFromLocationCode("CY01");
        agvTaskDetail.setContainerCode(trayCode);
        String s = commonUtil.httpPost("http://localhost:9046/task/create", JSON.toJSONString(agvSendTask));
        JSONObject jsonObject = JSON.parseObject(s);
        if (jsonObject.get("code").equals("0")) {
            tasksRepository.save(tasks);
            agvTasksRepository.save(agvTasks);
            agvTaskDetailRepository.save(agvTaskDetail);
            return "success";
        }
        return "agv未响应，请重新扫描入库";
    }

    @Override
    public String cancelByOutBound(String id) {
        Orders orders = ordersRepository.findById(id).orElse(null);
        if (null != orders) {
            List<OrderDetail> byMainId = orderDetailRepository.findByMainId(id);
            List<String> collect = byMainId.stream().map(OrderDetail::getOrderDetailCode).collect(Collectors.toList());
            List<AgvTasks> agvTasksByBillNumbers = agvTasksRepository.findAgvTasksByBillNumbers(collect);
            List<String> collect1 = agvTasksByBillNumbers.stream().map(AgvTasks::getTaskGroupCode).collect(Collectors.toList());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("taskCodes", collect1);
            String s = commonUtil.httpPost(agvIp + ":" + agvPort + "/task/cancel", jsonObject.toJSONString());
            JSONObject jsonObject1 = JSON.parseObject(s);
            if (jsonObject1.getInteger("code") == 0) {
                return "取消成功！！";
            } else {
                return "AGV响应异常！！";
            }
        }
        return "未查询到该单据！！";
    }

    /**
     * AGV取箱完成回调
     */
    @Override
    public Result agvCallBack(String parma) {
        log.info("接收到AGV回调，" + parma);
        JSONObject jsonObject = JSON.parseObject(parma);
        String taskCode = jsonObject.getString("taskCode"); // 业务任务号
        String eventType = jsonObject.getString("eventType");
        String status = jsonObject.getString("status");
        String containerCode = jsonObject.getString("containerCode");
        String locationCode = jsonObject.getString("locationCode");
        String robotCode = jsonObject.getString("robotCode");
        String stationCode = jsonObject.getString("stationCode");
        switch (eventType) {
            case "task":    // 任务完成
                if (status.equals("success")) {
                    AgvTasks agvTasksByBillNumber = agvTasksRepository.findAgvTasksByBillNumber(taskCode);
                    //根据任务号去agv任务表查询任务类型，分入库·出库·处理
                    //出库
                    if (null != agvTasksByBillNumber && agvTasksByBillNumber.getTaskType().equals("carry")) {
                        log.info("出库任务 ：WMS任务详细号" + taskCode + "已完成");
                        if (null != agvTasksByBillNumber.getStatus() && agvTasksByBillNumber.getStatus() == 2) {
                            return new Result(0,"success",new JSONObject());
                        }
                        TaskDetail taskDetails = taskDetailRepository.getTaskDetailByTaskCode(taskCode);
                        if (taskDetails.getStatus() == 1 || taskDetails.getStatus() == 4) {

                        } else {
                            return new Result(0,"success",new JSONObject());
                        }
                        taskDetails.setStatus(3);
                        taskDetailRepository.save(taskDetails);
                        Tasks tasks = tasksRepository.findById(taskDetails.getTaskId()).orElse(null);
                        List<TaskDetail> taskDetailsByTaskId = taskDetailRepository.getTaskDetailsByTaskId(tasks.getId());
                        boolean f = false;
                        for (TaskDetail taskDetail : taskDetailsByTaskId) {
                            if (taskDetail.getStatus() == 1) {
                                f = true;
                                break;
                            }
                        }
                        if (!f) {
                            tasks.setStatus(2);
                            tasks.setUpdateTime(new Timestamp(new Date().getTime()));
                            tasks.setUpdateBy("admin");
                        }
                        OrderDetail orderDetail = orderDetailRepository.findByOrderDetailCode(taskDetails.getSourceId());
                        orderDetail.setActQty(orderDetail.getActQty().add(taskDetails.getPkQty()));
                        Orders orders = ordersRepository.findById(orderDetail.getMainId()).orElse(null);
                        log.info("已出货完成" + taskDetails.getBoxNumber() + "的箱号，并改变数量");
                        List<Tasks> tasksList = tasksRepository.findByTaskCodeList(orderDetail.getOrderDetailCode());
                        boolean flag = false;
                        for (Tasks tasks1 : tasksList) {
                            if (tasks1.getStatus() != 2) {
                                flag = true;
                                break;
                            }
                        }
                        if (!flag) {
                            orderDetail.setStatus(2);
                            orderDetail.setUpdateTime(new Timestamp(new Date().getTime()));
                        }
                        List<OrderDetail> orderDetails = orderDetailRepository.findByMainId(orderDetail.getMainId());
                        boolean order = false;
                        for (OrderDetail detail : orderDetails) {
                            if (detail.getStatus() != 2) {
                                order = true;
                                break;
                            }
                        }

                        if (!order) {
                            orders.setOrderStatus(2);
                            orders.setUpdateTime(new Timestamp(new Date().getTime()));
                            orders.setUpdateBy("admin");
                            orders.setActQty(orders.getPlanQty());
                        }
                        agvTasksByBillNumber.setStatus(2);
                        agvTasksByBillNumber.setUpdateTime(new Timestamp(new Date().getTime()));
                        agvTasksByBillNumber.setUpdateBy("admin");
                        List<AgvTaskDetail> agvTaskDetailByMainId = agvTaskDetailRepository.getAgvTaskDetailByMainId(agvTasksByBillNumber.getId());
                        for (AgvTaskDetail agvTaskDetail : agvTaskDetailByMainId) {
                            agvTaskDetail.setStatus(2);
                            agvTaskDetail.setUpdateTime(new Timestamp(new Date().getTime()));
                            agvTaskDetail.setUpdateBy("admin");
                        }
                        tasksRepository.save(tasks);
                        agvTasksRepository.save(agvTasksByBillNumber);
                        agvTaskDetailRepository.saveAll(agvTaskDetailByMainId);
                        ordersRepository.save(orders);
                        orderDetailRepository.save(orderDetail);
                        boolean complete = false;
                        if (orders.getOrderStatus() == 2) {
                            complete = true;
                        }
                        /** 全部完成后发送至sccs */
                        if (complete) {
                            orders.setOrderStatus(2);
                            ordersRepository.save(orders);
                            List<String> collect = orderDetails.stream().map(OrderDetail::getOrderDetailCode).collect(Collectors.toList());
                            List<Tasks> byTaskCodes = tasksRepository.findByTaskCodes(collect);
                            List<String> collect1 = byTaskCodes.stream().map(Tasks::getId).collect(Collectors.toList());
                            List<TaskDetail> taskDetailsByTaskIds = taskDetailRepository.getTaskDetailsBySourceIds(collect);
                            if (orders.getOrderType() == 1) {
                                List<JSONObject> jsonObjectList = new ArrayList<>();
                                for (TaskDetail taskDetail : taskDetailsByTaskIds) {
                                    JSONObject jsonObject1 = new JSONObject();
                                    jsonObject1.put("pd_list", orders.getSourceDocument());
                                    jsonObject1.put("el_no", taskDetail.getEl_no());
                                    jsonObject1.put("pk_list", taskDetail.getPkList());
                                    jsonObject1.put("lot_no", taskDetail.getLotNo());
                                    jsonObject1.put("vmi_code", null != taskDetail.getVmiCode() ? taskDetail.getVmiCode() : "");
                                    jsonObject1.put("pk_qty", taskDetail.getPkQty());
                                    jsonObject1.put("el_unit", taskDetail.getEl_unit());
                                    jsonObject1.put("rtd_user", "admin");
                                    jsonObjectList.add(jsonObject1);
                                }
                                JSONObject jsonObject1 = new JSONObject();
                                jsonObject1.put("Sjson", JSON.toJSONString(jsonObjectList));
                                log.info("来源单据号为" + orders.getSourceDocument() + "销售随车单完成发送给sccs" + jsonObjectList);
                                String s = commonUtil.httpPost("http://137.40.151.241:9527/RTDSXWMS/WMSImportPD08", jsonObject1);
                                String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                                log.info("来源单据号为" + orders.getSourceDocument() + "销售随车单完成sccs回调返回" + resp);
                                JSONObject returnJson = JSON.parseObject(resp);
                                if (returnJson.getBoolean("tran_flg")) {
                                    orders.setIsSendSccs(1);
                                    ordersRepository.save(orders);
                                } else {
                                    log.info("来源单据号为" + orders.getSourceDocument() + "销售随车单推送sccs失败，返回 ：" + resp);
                                }
                            } else if (orders.getOrderType() == 2) {
                                List<JSONObject> jsonObjectList = new ArrayList<>();
                                for (TaskDetail taskDetail : taskDetailsByTaskIds) {
                                    JSONObject jsonObject1 = new JSONObject();
                                    jsonObject1.put("pd_list", orders.getSourceDocument());
                                    jsonObject1.put("el_no", taskDetail.getEl_no());
                                    jsonObject1.put("pk_list", taskDetail.getPkList());
                                    jsonObject1.put("lot_no", taskDetail.getLotNo());
                                    jsonObject1.put("vmi_code", null != taskDetail.getVmiCode() ? taskDetail.getVmiCode() : "");
                                    jsonObject1.put("pk_qty", taskDetail.getPkQty());
                                    jsonObject1.put("el_unit", taskDetail.getEl_unit());
                                    jsonObject1.put("rtd_user", "admin");
                                    jsonObjectList.add(jsonObject1);
                                }
                                JSONObject jsonObject1 = new JSONObject();
                                jsonObject1.put("Sjson", JSON.toJSONString(jsonObjectList));
                                log.info("来源单据号为" + orders.getSourceDocument() + "转仓随车单完成发送给sccs" + jsonObjectList);
                                String s = commonUtil.httpPost("http://137.40.151.241:9527/RTDSXWMS/WMSImportPD03", jsonObject1);
                                String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                                log.info("来源单据号为" + orders.getSourceDocument() + "转仓随车单完成sccs回调返回" + resp);
                                JSONObject returnJson = JSON.parseObject(resp);
                                if (returnJson.getBoolean("tran_flg")) {
                                    orders.setIsSendSccs(1);
                                    ordersRepository.save(orders);
                                } else {
                                    log.info("来源单据号为" + orders.getSourceDocument() + "转仓随车单推送sccs失败，返回 ：" + resp);
                                }
                            } else if (orders.getOrderType() == 3) {
                                List<JSONObject> jsonObjectList = new ArrayList<>();
                                for (TaskDetail taskDetail : taskDetailsByTaskIds) {
                                    JSONObject jsonObject1 = new JSONObject();
                                    jsonObject1.put("pd_list", orders.getSourceDocument());
                                    jsonObject1.put("el_no", taskDetail.getEl_no());
                                    jsonObject1.put("pk_list", taskDetail.getPkList());
                                    jsonObject1.put("lot_no", taskDetail.getLotNo());
                                    jsonObject1.put("vmi_code", null != taskDetail.getVmiCode() ? taskDetail.getVmiCode() : "");
                                    jsonObject1.put("pk_qty", taskDetail.getPkQty());
                                    jsonObject1.put("el_unit", taskDetail.getEl_unit());
                                    jsonObject1.put("rtd_user", "admin");
                                    jsonObjectList.add(jsonObject1);
                                }
                                JSONObject jsonObject1 = new JSONObject();
                                jsonObject1.put("Sjson", JSON.toJSONString(jsonObjectList));
                                log.info("来源单据号为" + orders.getSourceDocument() + "发送给sccs" + jsonObjectList);
                                String s = commonUtil.httpPost("http://137.40.151.241:9527/RTDSXWMS/WMSImportPD07", jsonObject1);
                                String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                                log.info("来源单据号为" + orders.getSourceDocument() + "sccs回调返回" + resp);
                                JSONObject returnJson = JSON.parseObject(resp);
                                if (returnJson.getBoolean("tran_flg")) {
                                    orders.setIsSendSccs(1);
                                    ordersRepository.save(orders);
                                } else {
                                    log.info("来源单据号为" + orders.getSourceDocument() + "成本中心领用推送sccs失败，返回 ：" + resp);
                                }
                            } else if (orders.getOrderType() == 4) {
                                List<JSONObject> jsonObjectList = new ArrayList<>();
                                for (TaskDetail taskDetail : taskDetailsByTaskIds) {
                                    JSONObject jsonObject1 = new JSONObject();
                                    jsonObject1.put("mr_list", orders.getSourceDocument());
                                    jsonObject1.put("el_no", taskDetail.getEl_no());
                                    jsonObject1.put("pk_list", taskDetail.getPkList());
                                    jsonObject1.put("lot_no", taskDetail.getLotNo());
                                    jsonObject1.put("vmi_code", null != taskDetail.getVmiCode() ? taskDetail.getVmiCode() : "");
                                    jsonObject1.put("pk_qty", taskDetail.getPkQty());
                                    jsonObject1.put("el_unit", taskDetail.getEl_unit());
                                    jsonObject1.put("rtd_user", "admin");
                                    jsonObjectList.add(jsonObject1);
                                }
                                JSONObject jsonObject1 = new JSONObject();
                                jsonObject1.put("Sjson", JSON.toJSONString(jsonObjectList));
                                log.info("来源单据号为" + orders.getSourceDocument() + "成本中心领用发送给sccs" + jsonObjectList);
                                String s = commonUtil.httpPost("http://137.40.151.241:9527/RTDSXWMS/WMSImportMR02", jsonObject1);
                                String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                                log.info("来源单据号为" + orders.getSourceDocument() + "成本中心领用sccs回调返回" + resp);
                                JSONObject returnJson = JSON.parseObject(resp);
                                if (returnJson.getBoolean("tran_flg")) {
                                    orders.setIsSendSccs(1);
                                    ordersRepository.save(orders);
                                } else {
                                    log.info("来源单据号为" + orders.getSourceDocument() + "成本中心领用推送sccs失败，返回 ：" + resp);
                                }

                            } else if (orders.getOrderType() == 5) {
                                List<JSONObject> jsonObjectList = new ArrayList<>();
                                for (TaskDetail taskDetail : taskDetailsByTaskIds) {
                                    JSONObject jsonObject1 = new JSONObject();
                                    jsonObject1.put("el_no", taskDetail.getEl_no());
                                    jsonObject1.put("mr_list", orders.getSourceDocument());
                                    jsonObject1.put("vmi_code", null != taskDetail.getVmiCode() ? taskDetail.getVmiCode() : "");
                                    jsonObject1.put("lot_no", taskDetail.getLotNo());
                                    jsonObject1.put("pk_qty", taskDetail.getPkQty());
                                    jsonObject1.put("pk_list", taskDetail.getPkList());
                                    jsonObject1.put("rtd_user", "admin");
                                    jsonObjectList.add(jsonObject1);
                                }
                                JSONObject jsonObject1 = new JSONObject();
                                jsonObject1.put("Sjson", JSON.toJSONString(jsonObjectList));
                                log.info("来源单据号为" + orders.getSourceDocument() + "311转仓出库发送给sccs" + jsonObjectList);
                                String s = commonUtil.httpPost("http://137.40.151.241:9527/RTDSXWMS/WMSImportMR03", jsonObject1);
                                String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                                log.info("来源单据号为" + orders.getSourceDocument() + "311转仓出库sccs回调返回" + resp);
                                JSONObject returnJson = JSON.parseObject(resp);
                                if (returnJson.getBoolean("tran_flg")) {
                                    orders.setIsSendSccs(1);
                                    ordersRepository.save(orders);
                                } else {
                                    log.info("来源单据号为" + orders.getSourceDocument() + "311转仓出库推送sccs失败，返回 ：" + resp);
                                }

                            } else if (orders.getOrderType() == 6) {
                                List<JSONObject> jsonObjectList = new ArrayList<>();
                                for (TaskDetail taskDetail : taskDetailsByTaskIds) {
                                    JSONObject jsonObject1 = new JSONObject();
                                    jsonObject1.put("el_no", taskDetail.getEl_no());
                                    jsonObject1.put("mr_list", orders.getSourceDocument());
//                                    jsonObject1.put("vmi_code", null != taskDetail.getVmiCode()?taskDetail.getVmiCode():"");
                                    jsonObject1.put("lot_no", taskDetail.getLotNo());
                                    jsonObject1.put("pk_qty", taskDetail.getPkQty());
                                    jsonObject1.put("pk_list", taskDetail.getPkList());
                                    jsonObject1.put("rtd_user", "admin");
                                    jsonObjectList.add(jsonObject1);
                                }
                                JSONObject jsonObject1 = new JSONObject();
                                jsonObject1.put("Sjson", JSON.toJSONString(jsonObjectList));
                                log.info("来源单据号为" + orders.getSourceDocument() + "411转仓出库发送给sccs" + jsonObjectList);
                                String s = commonUtil.httpPost("http://137.40.151.241:9527/RTDSXWMS/WMSImportMR03", jsonObject1);
                                String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                                log.info("来源单据号为" + orders.getSourceDocument() + "411转仓出库sccs回调返回" + resp);
                                JSONObject returnJson = JSON.parseObject(resp);
                                if (returnJson.getBoolean("tran_flg")) {
                                    orders.setIsSendSccs(1);
                                    ordersRepository.save(orders);
                                } else {
                                    log.info("来源单据号为" + orders.getSourceDocument() + "311转仓出库推送sccs失败，返回 ：" + resp);
                                }

                            }
                        }
                        //入库
                    }
                }
                break;
            case "tote_load":   // 取箱完成
                /** 释放库位 */
                AgvTasks agvTasksByBillNumber = agvTasksRepository.findAgvTasksByBillNumber(taskCode);
                if (null != agvTasksByBillNumber && null != agvTasksByBillNumber.getStatus() && agvTasksByBillNumber.getStatus() == 2){
                    return new Result(0,"success",new JSONObject());
                }
                if (null != agvTasksByBillNumber && agvTasksByBillNumber.getTaskType().equals("空料箱出库")) {
                    if (status.equals("success")) {
                        if (null != agvTasksByBillNumber.getStatus() && agvTasksByBillNumber.getStatus() == 2){
                            return new Result(0,"success",new JSONObject());
                        }
                        Location location = locationRepository.getLocationsByLocationCode(locationCode);
                        log.info("空料箱出库 :" + location.getLocationCode() + "-" + location.getTrayCode());
                        location.setStatus(0);  // 0--空闲，释放库位
                        location.setTrayCode("");
                        locationRepository.save(location);
                        agvTasksByBillNumber.setStatus(2);
                        agvTasksRepository.save(agvTasksByBillNumber);
                        Tasks tasks = tasksRepository.findByTaskCode(taskCode);
                        if (null != tasks){
                            tasks.setStatus(2);
                            tasksRepository.save(tasks);
                        }
                        return new Result(0,"success",new JSONObject());
                    } else {
                        Location location = locationRepository.getLocationsByLocationCode(locationCode);
                        log.info("空料箱出库取箱失败 :" + location.getLocationCode() + "-" + location.getTrayCode());
                        location.setStatus(2);  // 2--禁用库位
                        locationRepository.save(location);
                        return new Result(0,"success",new JSONObject());
                    }
                } else if (null != agvTasksByBillNumber && agvTasksByBillNumber.getTaskType().equals("抽检出库")) {
                    if (status.equals("success")) {
                        Location location = locationRepository.getLocationsByLocationCode(locationCode);
                        log.info("抽检出库 :" + location.getLocationCode() + "-" + location.getTrayCode());
                        location.setStatus(0);  // 0--空闲，释放库位
                        location.setTrayCode("");
                        locationRepository.save(location);
                        agvTasksByBillNumber.setStatus(2);
                        agvTasksRepository.save(agvTasksByBillNumber);
                        return new Result(0,"success",new JSONObject());
                    } else {
                        Location location = locationRepository.getLocationsByLocationCode(locationCode);
                        log.info("空料箱出库取箱失败 :" + location.getLocationCode() + "-" + location.getTrayCode());
                        location.setStatus(2);  // 2--禁用库位
                        locationRepository.save(location);
                        return new Result(0,"success",new JSONObject());
                    }
                } else if (null != agvTasksByBillNumber && agvTasksByBillNumber.getTaskType().equals("移库")) {
                    Location location = locationRepository.getLocationsByLocationCode(locationCode);
                    log.info("移库任务:" + taskCode + " - " + location.getLocationCode() + " - " + location.getTrayCode());
                    location.setStatus(0);  // 0--空闲，释放库位
                    location.setTrayCode("");
                    locationRepository.save(location);
                    return new Result(0,"success",new JSONObject());
                }
                break;
            case "tote_unload": // 放箱完成
                AgvTasks agvTasksByBillNumber1 = agvTasksRepository.findAgvTasksByBillNumber(taskCode);
                if (null != agvTasksByBillNumber1 && null != agvTasksByBillNumber1.getStatus() && agvTasksByBillNumber1.getStatus() == 2){
                    return new Result(0,"success",new JSONObject());
                }
                //有料的料箱回库
                if (null != agvTasksByBillNumber1 && agvTasksByBillNumber1.getTaskType().equals("冻结出库")) {
                    Location location = locationRepository.findLocationByLocationCode(locationCode);
//                    Inventory inventory = inventoryRepository.findByTrayCodeTop(containerCode);
//                    inventoryRepository.delete(inventory);
                    location.setStatus(0);
                    location.setUpdateTime(new Timestamp(new Date().getTime()));
                    locationRepository.save(location);
                    agvTasksByBillNumber1.setStatus(2);
                    agvTasksRepository.save(agvTasksByBillNumber1);
                    return new Result(0,"success",new JSONObject());
                } else if (null != agvTasksByBillNumber1 && agvTasksByBillNumber1.getTaskType().equals("解冻出库")) {
                    Location location = locationRepository.findLocationByLocationCode(locationCode);
//                    Inventory inventory = inventoryRepository.findByTrayCodeTop(containerCode);
//                    inventoryRepository.delete(inventory);
                    location.setStatus(0);
                    location.setUpdateTime(new Timestamp(new Date().getTime()));
                    locationRepository.save(location);
                    agvTasksByBillNumber1.setStatus(2);
                    agvTasksRepository.save(agvTasksByBillNumber1);
                    return new Result(0,"success",new JSONObject());
                } else if (null != agvTasksByBillNumber1 && agvTasksByBillNumber1.getTaskType().equals("有料的料箱回库")) {
                    log.info("有料的料箱回库收到" + taskCode);
                    Location locationByLocationCode = locationRepository.findLocationByLocationCode(locationCode);
                    Inventory byTrayCode = inventoryRepository.findByTrayCodeTop(containerCode);
                    byTrayCode.setIsHold(0);
                    byTrayCode.setHoldQuantity(new BigDecimal(0));
                    inventoryRepository.save(byTrayCode);
                    locationByLocationCode.setTrayCode(containerCode);
                    locationByLocationCode.setStatus(1);
                    locationByLocationCode.setUpdateTime(new Timestamp(new Date().getTime()));
                    locationRepository.save(locationByLocationCode);
                    agvTasksByBillNumber1.setStatus(2);
                    agvTasksRepository.save(agvTasksByBillNumber1);
                    TaskDetail taskDetail = taskDetailRepository.getTaskDetailByPkListAndTypeOne(byTrayCode.getBoxNumber());
                    if (null != taskDetail) {
                        JSONObject agvTask = new JSONObject();
                        agvTask.put("taskType", "tote_outbound");
//                        agvTask.put("groupPriority", 1);
                        agvTask.put("taskGroupCode", UuidUtil.genCode());
                        List<JSONObject> tasks = new ArrayList<>();
                        JSONObject task = new JSONObject();
                        task.put("taskCode", taskDetail.getTaskCode());
                        task.put("taskPriority", 1000);
                        taskDetail.setStatus(4);
                        JSONObject taskDescribe = new JSONObject();
                        taskDescribe.put("containerCode", taskDetail.getTrayCode());
                        taskDescribe.put("storageTag", "");
                        taskDescribe.put("fromLocationCode", "");
                        List<String> toLocationCode = new ArrayList<>();
                        toLocationCode.add("CY01");
                        taskDetail.setStatus(4);
                        taskDescribe.put("toStationCode", toLocationCode);
                        task.put("taskDescribe", taskDescribe);
                        tasks.add(task);
                        agvTask.put("tasks", tasks);
                        AgvTasks agvTasks = new AgvTasks();
                        agvTasks.setId(UuidUtil.genCode());
                        agvTasks.setStatus(1);
                        agvTasks.setTaskType("carry");
                        agvTasks.setCreateTime(new Timestamp(new Date().getTime()));
                        agvTasks.setTaskGroupCode(agvTask.getString("taskGroupCode"));
                        agvTasks.setBillNumber(taskDetail.getTaskCode());
                        agvTasks.setCreateBy(SecurityUtils.getCurrentUsername());
                        agvTasksRepository.save(agvTasks);
                        taskDetailRepository.save(taskDetail);
                        String s = commonUtil.httpPost("http://" + agvIp + ":" + agvPort + "/task/create", JSON.toJSONString(agvTask));
                        Result result = JSON.parseObject(s, Result.class);
                        log.info("在途货物出库收到agv反馈" + result);
                    }
                    return new Result(0,"success",new JSONObject());
                }
                //空料箱回库
                else if (null != agvTasksByBillNumber1 && agvTasksByBillNumber1.getTaskType().equals("空料箱回库")) {
                    Inventory byTrayCodeTop = inventoryRepository.findByTrayCodeTop(containerCode);
                    if (null != byTrayCodeTop && byTrayCodeTop.getAvailableQuantity().compareTo(new BigDecimal(0)) <= 0) {
                        inventoryRepository.deleteById(byTrayCodeTop.getId());
                    }
                    log.info("空料箱回库收到" + taskCode);
                    Location locationByLocationCode = locationRepository.findLocationByLocationCode(locationCode);
                    locationByLocationCode.setTrayCode(containerCode);
                    locationByLocationCode.setUpdateTime(new Timestamp(new Date().getTime()));
                    locationByLocationCode.setStatus(3);
                    locationRepository.save(locationByLocationCode);
                    agvTasksByBillNumber1.setStatus(2);
                    agvTasksRepository.save(agvTasksByBillNumber1);
                    return new Result(0,"success",new JSONObject());
                } else if (null != agvTasksByBillNumber1 && agvTasksByBillNumber1.getTaskType().equals("抽检出库")) {
                    log.info("抽检出库放箱完成" + taskCode);
                    Tasks tasks = tasksRepository.getTaskByTaskCode(agvTasksByBillNumber1.getBillNumber());
                    if (null == tasks) {
                        tasks = tasksRepository.getCheckOutTaskByTrayCodeAndStatus(containerCode, 1);
                    }
                    tasks.setStatus(2); // 2-已完成
                    tasks.setEndTime(new Timestamp(new Date().getTime()));
                    tasksRepository.save(tasks);

                    agvTasksByBillNumber1.setStatus(2); // 2--任务完成
                    agvTasksRepository.save(agvTasksByBillNumber1);
                    return new Result(0,"success",new JSONObject());

                } else if (null != agvTasksByBillNumber1 && agvTasksByBillNumber1.getTaskType().equals("抽检回库")) {
                    log.info("抽检回库" + taskCode);
                    CheckRecord checkRecord = checkRecordRepository.getCheckRecordByTrayCodeAndStatus(containerCode, 1);
                    checkRecord.setCheckStatus(2);  // 2--抽检回库完成，抽检任务完成
                    checkRecordRepository.save(checkRecord);

                    /** 释放库存 */
                    Inventory inventory = inventoryRepository.findByTrayCodeTop(containerCode);
                    inventory.setIsHold(0);
                    inventory.setAvailableQuantity(inventory.getHoldQuantity());
                    inventory.setHoldQuantity(new BigDecimal(0));
                    inventoryRepository.save(inventory);

                    Location location = locationRepository.findLocationByLocationCode(locationCode);
                    location.setStatus(1);  // 1--占用
                    location.setTrayCode(containerCode);
                    locationRepository.save(location);

                    agvTasksByBillNumber1.setStatus(2); // 2--任务完成
                    agvTasksRepository.save(agvTasksByBillNumber1);
                    return new Result(0,"success",new JSONObject());

                } else if (null != agvTasksByBillNumber1 && agvTasksByBillNumber1.getTaskType().equals("立库出暂存区")) {
                    Inventory inventory = inventoryRepository.findByTrayCodeTop(containerCode);
                    Location location = locationRepository.findLocationByLocationCode(locationCode);
                    if (null != inventory) {
                        inventory.setTrayCode("");
                        inventory.setWarehouseLocation("暂存区");
                        inventory.setLocationCode("暂存区");
                        inventory.setWarehouseCode("立体仓");
                        inventoryRepository.save(inventory);
                    }
                    if (null != location){
                        location.setStatus(2);
                        location.setTrayCode(containerCode);
                        locationRepository.save(location);
                        agvTasksByBillNumber1.setStatus(2);
                        agvTasksRepository.save(agvTasksByBillNumber1);
                    }
                    return new Result(0,"success",new JSONObject());
                } else if (null != agvTasksByBillNumber1 && agvTasksByBillNumber1.getTaskType().equals("移库")) {
                    Tasks tasks = tasksRepository.getTaskByTaskCode(taskCode);
                    Location location = locationRepository.findLocationByLocationCode(locationCode);
                    if (tasks.getElName().equals("料箱")) {
                        location.setStatus(3);  // 3--托盘占用
                    }else {
                        location.setStatus(1);  // 1--占用
                    }
                    location.setTrayCode(containerCode);
                    locationRepository.save(location);

                    /** 判断有没有源单编码 */
                    if (!commonUtil.isStringNotEmpty(tasks.getSourceCode())) {  // 没有源单编码，则说明是1阶段移库
                        tasks.setStatus(2); // 2--任务完成
                        if (tasks.getElName().equals("料箱")) {

                        }else { // 有库存的载具
                            /** 更新库存 */
                            Inventory inventory = inventoryRepository.findByTrayCodeTop(containerCode);
                            inventory.setWarehouseLocation(locationCode);
                            inventoryRepository.save(inventory);
                        }

                        /** 下发二阶段的移库任务给AGV */
                        Tasks tasksLevel2 = tasksRepository.findBySourceCodeTop(taskCode);  // 根据1阶段的taskCode作为源单编码，查找2阶段的任务

                        /** 查找对应的AGVTasks */
                        AgvTasks agvTasks = agvTasksRepository.findAgvTasksByBillNumber(tasksLevel2.getTaskCode());
                        List<AgvTaskDetail> agvTaskDetailList = agvTaskDetailRepository.getAgvTaskDetailByMainId(agvTasks.getId());

                        /** 下发任务给AGV */
                        /** 下发给AGV */
                        JSONObject jsonObject1 = new JSONObject();
                        jsonObject1.put("taskType", "carry");
                        jsonObject1.put("taskGroupCode", agvTasks.getTaskGroupCode());
//                        jsonObject1.put("groupPriority", 1);
                        JSONArray jsonArray = new JSONArray();

                        JSONObject jsonObject2 = new JSONObject();
                        jsonObject2.put("taskCode", tasksLevel2.getTaskCode());   // WMS-tasks主表任务号，这里发送给AGV的任务号， AGV回调以后会返回这个任务号给我。这里不严谨，但是延续之前的逻辑，不做更改了
                        jsonObject2.put("taskPriority", 1);

                        JSONObject jsonObject3 = new JSONObject();
                        jsonObject3.put("containerCode", tasksLevel2.getTrayCode()); // 料箱号
                        jsonObject3.put("storageTag", "");   // 留空
                        jsonObject3.put("containerType", "");
                        jsonObject3.put("fromLocationCode", tasksLevel2.getLocationFrom());    // 起始库位号
                        jsonObject3.put("toLocationCode", tasksLevel2.getLocationTo());    // 目标库位号
                        jsonObject3.put("toStationCode", "");   // 出库的目标操作台编号 留空

                        jsonObject2.put("taskDescribe", jsonObject3);
                        jsonArray.add(jsonObject2);

                        jsonObject1.put("tasks", jsonArray);
                        String url = "http://" + agvIp + ":" + agvPort + "/task/create";
                        log.info("空料箱移库任务，发送给AGV, " + jsonObject1);
                        String resp = commonUtil.httpPost(url, jsonObject1);
                        Result result = JSON.parseObject(resp, Result.class);
                        log.info("空料箱移库任务，接收到AGV反馈, " + resp);
                        if (result.getCode() != 0) {
                            log.info(agvTasks.getTaskGroupCode() + ", 移库任务AGV响应异常，原因：" + result);
                            agvTasks.setStatus(3);  // 3--异常
                            agvTasksRepository.save(agvTasks);

                        } else {
                            /** 修改任务状态 */
                            tasksLevel2.setStatus(1); // 执行中
                            tasksRepository.save(tasks);

                            /** 修改AGV任务，和AGVTaskDetail的状态 */
                            agvTasks.setStatus(1);
                            agvTasksRepository.save(agvTasks);
                            for (AgvTaskDetail agvTaskDetail : agvTaskDetailList) {
                                agvTaskDetail.setStatus(1); // 1--执行中
                            }
                            agvTaskDetailRepository.saveAll(agvTaskDetailList);

                        }

                    }else { // 有源单编码，说明是2阶段移库,放箱完成后，查询新的理货任务
                        Inventory byTrayCodeTop = inventoryRepository.findByTrayCodeTop(containerCode);
                        if (null != byTrayCodeTop){
                            byTrayCodeTop.setWarehouseLocation(locationCode);
                            byTrayCodeTop.setLocationCode(locationCode);
                            inventoryRepository.save(byTrayCodeTop);
                        }
                        Location byTrayCode = locationRepository.findByTrayCode(containerCode);
                        if (null != byTrayCodeTop){
                            byTrayCode.setStatus(1);
                        }else{
                            byTrayCode.setStatus(3);
                        }
                        locationRepository.save(byTrayCode);
                        Calendar instance = Calendar.getInstance();
                        int hour = instance.get(Calendar.HOUR_OF_DAY);
                        if (!flag || hour <= 6 || hour > 22){
                            int result = inventoryService.generateTallyTasks();
                        }else{
                            tallyTasksRepository.deleteAll();
                        }


                    }
                }

                AgvTaskDetail byTaskCode = agvTaskDetailRepository.findByTaskCode(taskCode);
                if (null == byTaskCode) {
                    return new Result(102,"fail",new JSONObject());
                }
                if (null != byTaskCode.getFromLocationCode() && byTaskCode.getFromLocationCode().equals("暂存区")) {
                    Inventory inventory = inventoryRepository.findByTrayCodeTop(containerCode);
                    inventory.setIsHold(0);
                    inventory.setHoldQuantity(new BigDecimal(0));
                    inventoryRepository.save(inventory);
                    Location byTrayCode = locationRepository.findLocationByLocationCode(inventory.getWarehouseLocation());
                    byTrayCode.setStatus(1);
                    byTrayCode.setTrayCode(containerCode);
                    locationRepository.save(byTrayCode);
                    return new Result(0,"success",new JSONObject());
                }

                if (null != byTaskCode.getFromLocationCode() && byTaskCode.getFromLocationCode().equals("暂存区")) {
                    Inventory inventory = inventoryRepository.findByTrayCodeTop(containerCode);
                    inventory.setIsHold(0);
                    inventory.setHoldQuantity(new BigDecimal(0));
                    inventoryRepository.save(inventory);
                    Location byTrayCode = locationRepository.findLocationByLocationCode(inventory.getWarehouseLocation());
                    byTrayCode.setStatus(1);
                    byTrayCode.setTrayCode(containerCode);
                    locationRepository.save(byTrayCode);
                    return new Result(0,"success",new JSONObject());
                }

                AgvTasks agvTasks = agvTasksRepository.findById(byTaskCode.getMainId()).orElse(null);
                if (null == agvTasks) {
                    return new Result(102,"fail",new JSONObject());
                }
                TaskDetail taskDetailByTaskCode = taskDetailRepository.getTaskDetailByTaskCode(byTaskCode.getTaskCode());
                String wmsTaskCode = agvTasks.getBillNumber();
                log.info("接收到：" + taskDetailByTaskCode + "入库回调");
                Tasks tasks = tasksRepository.getTaskByTaskCode(wmsTaskCode);   // WMS
                tasks.setEndTime(new Timestamp(new Date().getTime()));
                tasks.setStatus(2); // 2--任务完成
                tasksRepository.save(tasks);
                /** 根据上报的箱号 查询收货明细 */
                ReceiptDetail receiptDetail = receiptDetailRepository.getReceiptDetailsByReceiptDetailCode(taskDetailByTaskCode.getSourceId());
                Receipt receipt = receiptRepository.findById(receiptDetail.getReceiptId()).orElse(null);
                if (!receipt.getStatus().equals("2")) {
                    if (receiptDetail.getStatus() != 2)
                        receipt.setActQty(receipt.getActQty().add(receiptDetail.getPkQty()));
                }
                receiptRepository.save(receipt);
                String mtBwart = receipt.getMtBwart();  // 移动类型
                Inventory inventory = inventoryRepository.getInventoryByMaterialCodeAndBoxNumber(receipt.getElNo(), receiptDetail.getPkList());
                inventory.setTrayCode(containerCode);
                inventory.setIsHold(0);
                inventory.setLocationCode(tasks.getLocationTo());   // 更新库存信息
                inventory.setWarehouseLocation(tasks.getLocationTo());
                log.info("更新了 + " + inventory.getBoxNumber() + "的库存信息");
                inventoryRepository.save(inventory);


                /** 可能要分入库 / 出库 不同的任务类型来处理  */
                /** 入库 */
                if (tasks.getTaskType() == 1) {
                    /** 上报SCCS 该箱号入库完成 */
                    /** 判断该料箱所属的入库单包含的料箱是否全部完成， 整张入库单完成后才上报入库完成 */
                    Location locationByLocationCode = locationRepository.findLocationByLocationCode(locationCode);
                    locationByLocationCode.setTrayCode(containerCode);
                    locationByLocationCode.setStatus(1);
                    locationRepository.save(locationByLocationCode);
                    int flag = 0;
                    receiptDetail.setStatus(2); // 2--完成
                    receiptDetailRepository.save(receiptDetail);
                    log.info(locationCode + ", 放箱完成, 并更改了入库单明细的状态。");

                    /** 检查同一个入库单下所有的主表和所有的明细 */
                    List<Receipt> receiptList = receiptRepository.getReceiptsByMtList(receipt.getMtList());
                    for (Receipt receipt1 : receiptList) {
                        List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt1.getId());
                        for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                            if (receiptDetail1.getStatus() != 2) { // 如果有未完成的
                                flag = 1;
                            }
                        }
                    }
                    if (!commonUtil.isStringNotEmpty(mtBwart)) {
                        /** 采购入库 */
                        /** 检查flag标志位  */
                        if (flag == 0) {    // 全部完成
                            /** 更新收货单状态 */
                            for (Receipt receipt1 : receiptList) {
                                receipt1.setStatus("2");  // 2--收货完成
                                receiptRepository.save(receipt1);
                            }
                            JSONObject jsonObject1 = new JSONObject();
                            jsonObject1.put("Sjson", receipt.getMtList());
                            String url = sccsIp + ":" + sccsPort + "/RTDSXWMS/WMSImportMT03A";
                            String s = commonUtil.httpPost(url, jsonObject1);
                            String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                            log.info("推送采购入库给SCCS的返回值，" + resp);
                            JSONObject respJson = JSON.parseObject(resp);
                            String tranFlg = respJson.getString("tran_flg");
                            if (tranFlg.equals("true")) {
                                for (Receipt receipt1 : receiptList) {
                                    receipt1.setIsSendSccs(1);  // 1--已推送
                                    receiptRepository.save(receipt1);
                                }
                            }
                        }
                    } else if (mtBwart.equals("成本中心入库")) {
                        /** 成本中心入库 */
                        if (flag == 0) {    // 全部完成
                            /** 更新收货单状态 */
                            for (Receipt receipt1 : receiptList) {
                                receipt1.setStatus("2");  // 2--收货完成
                                receiptRepository.save(receipt1);
                            }
                            List<JSONObject> jsonArray = new ArrayList<>();
                            for (Receipt receipt1 : receiptList) {
                                List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt1.getId());
                                for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                                    JSONObject jsonObject1 = new JSONObject();
                                    jsonObject1.put("mr_list", receipt1.getMtList());
                                    jsonObject1.put("el_no", receipt1.getElNo());
                                    jsonObject1.put("pk_list", receiptDetail1.getPkList());
                                    jsonObject1.put("lot_no", receipt1.getLotNo());
                                    jsonObject1.put("pk_qty", receiptDetail1.getPkQty());
                                    jsonObject1.put("el_unit", receipt1.getElUnit());
                                    jsonObject1.put("rtd_user", receipt1.getRtdUser());
                                    jsonArray.add(jsonObject1);
                                }
                            }
                            log.info("成本中心入库推送给SCCS，" + jsonArray);
                            String url = sccsIp + ":" + sccsPort + "/RTDSXWMS/WMSImportMR01";
                            JSONObject jsonObjectSend = new JSONObject();
                            jsonObjectSend.put("Sjson", JSON.toJSONString(jsonArray));
                            String resp = commonUtil.httpPost(url, JSON.toJSON(jsonObjectSend));
                            log.info("成本中心入库SCCS返回，" + resp);
                            String respString = StrUtil.strip(resp, "\"").replaceAll("\\\\", "");
                            JSONObject jsonObjectResp = JSON.parseObject(respString);
                            String tranFlg = jsonObjectResp.getString("tran_flg");
                            if (tranFlg.equals("true")) {
                                for (Receipt receipt1 : receiptList) {
                                    receipt1.setIsSendSccs(1);  // 1--已推送
                                    receiptRepository.save(receipt1);
                                }
                            }
                        }
                    } else if (mtBwart.equals("免费入库")) {
                        /** 免费入库 */
                        if (flag == 0) {    // 全部完成
                            List<JSONObject> jsonArray = new ArrayList<>();
                            /** 更新收货单状态 */
                            for (Receipt receipt1 : receiptList) {
                                receipt1.setStatus("2");  // 2--收货完成
                                receiptRepository.save(receipt1);
                            }
                            for (Receipt receipt1 : receiptList) {
                                List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt1.getId());
                                for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                                    JSONObject jsonObject1 = new JSONObject();
                                    jsonObject1.put("mr_list", receipt1.getMtList());   // 入库单号
                                    jsonObject1.put("el_no", receipt1.getElNo());   // 物料编码
                                    jsonObject1.put("pk_list", receiptDetail1.getPkList()); // 箱号
                                    jsonObject1.put("lot_no", receipt1.getLotNo()); // 批次号
                                    jsonObject1.put("pk_qty", receiptDetail1.getPkQty());   // 数量
                                    jsonObject1.put("su_no", receipt1.getSuNo());  //   供应商代码
                                    jsonArray.add(jsonObject1);
                                }
                            }
                            log.info("免费入库推送给SCCS，" + jsonArray);
                            JSONObject jsonObject1 = new JSONObject();
                            jsonObject1.put("Sjson", JSON.toJSONString(jsonArray));
                            String url = sccsIp + ":" + sccsPort + "/RTDSXWMS/WMSImportMR01";
                            String s = commonUtil.httpPost(url, jsonObject1.toJSONString());
                            String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                            log.info("免费入库SCCS返回，" + resp);
                            JSONObject jsonObjectResp = JSON.parseObject(resp);
                            String tranFlg = jsonObjectResp.getString("tran_flg");
                            if (tranFlg.equals("true")) {
                                for (Receipt receipt1 : receiptList) {
                                    receipt1.setStatus("2");  // 2--收货完成
                                    receipt1.setIsSendSccs(1);  // 1--已推送
                                    receiptRepository.save(receipt1);
                                }
                            }
                        }
                    } else if (mtBwart.equals("311")) {
                        /** 转仓入库 */
                        if (flag == 0) {    // 全部完成
                            /** 更新收货单状态 */
                            for (Receipt receipt1 : receiptList) {
                                receipt1.setStatus("2");  // 2--收货完成
                                receiptRepository.save(receipt1);
                            }
                            List<JSONObject> jsonObjectList = new ArrayList<>();
                            for (Receipt receipt1 : receiptList) {
                                List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt1.getId());
                                for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                                    JSONObject jsonObject1 = new JSONObject();
                                    jsonObject1.put("mr_list", receipt1.getMtList());   // 入库单号
                                    jsonObject1.put("el_no", receipt1.getElNo());   // 物料编码
                                    jsonObject1.put("el_name", receipt1.getElName());    // 物料名称
                                    jsonObject1.put("pk_list", receiptDetail1.getPkList()); // 箱号
                                    jsonObject1.put("lot_no", receipt1.getLotNo()); // 批次号
                                    jsonObject1.put("pk_qty", receiptDetail1.getPkQty());   // 数量
                                    jsonObject1.put("rtd_user", "admin");   // 数量
                                    jsonObject1.put("vmi_code", null == receiptDetail1.getVmiCode() ? "" : receiptDetail1.getVmiCode());   // 数量
                                    jsonObjectList.add(jsonObject1);
                                }
                            }
                            log.info("转仓入库推送给SCCS，" + jsonObjectList);
                            String url = sccsIp + ":" + sccsPort + "/RTDSXWMS/WMSImportMR03";
                            JSONObject jsonObjectSend = new JSONObject();
                            jsonObjectSend.put("Sjson", JSON.toJSONString(jsonObjectList));
                            String s = commonUtil.httpPost(url, JSON.toJSON(jsonObjectSend));
                            String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                            log.info("转仓入库SCCS返回，" + resp);
                            JSONObject jsonObjectResp = JSON.parseObject(resp);
                            String tranFlg = jsonObjectResp.getString("tran_flg");
                            if (tranFlg.equals("true")) {
                                for (Receipt receipt1 : receiptList) {
                                    receipt1.setIsSendSccs(1);  // 1--已推送
                                    receiptRepository.save(receipt1);
                                }
                            }
                        }
                    } else if (mtBwart.equals("客户退货")) {
                        /** 客户退货 */
                        if (flag == 0) {    // 全部完成
                            /** 更新收货单状态 */
                            for (Receipt receipt1 : receiptList) {
                                receipt1.setStatus("2");  // 2--收货完成
                                receiptRepository.save(receipt1);
                            }
                            List<JSONObject> jsonObjectList = new ArrayList<>();
                            for (Receipt receipt1 : receiptList) {
                                List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt1.getId());
                                for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                                    JSONObject jsonObject1 = new JSONObject();
                                    jsonObject1.put("pd_list", receipt1.getMtList());   // 入库单号
                                    jsonObject1.put("el_no", receipt1.getElNo());   // 物料编码
                                    jsonObject1.put("pk_list", receiptDetail1.getPkList()); // 箱号
                                    jsonObject1.put("lot_no", receipt1.getLotNo()); // 批次号
                                    jsonObject1.put("pk_qty", receiptDetail1.getPkQty());   // 数量
                                    jsonObject1.put("rtd_user", "admin");   // 数量
                                    jsonObject1.put("vmi_code", null == receiptDetail1.getVmiCode() ? "" : receiptDetail1.getVmiCode());   // 数量
                                    jsonObjectList.add(jsonObject1);
                                }
                            }
                            log.info("客户退货，推送给SCCS，" + jsonObjectList);
                            String url = sccsIp + ":" + sccsPort + "/RTDSXWMS/WMSImportPD07";
                            JSONObject jsonObjectSend = new JSONObject();
                            jsonObjectSend.put("Sjson", JSON.toJSONString(jsonObjectList));
                            String resp = commonUtil.httpPost(url, JSON.toJSON(jsonObjectSend));
                            log.info("客户退货，SCCS返回，" + resp);
                            String respString = StrUtil.strip(resp, "\"").replaceAll("\\\\", "");
                            JSONObject jsonObjectResp = JSON.parseObject(respString);
                            String tranFlg = jsonObjectResp.getString("tran_flg");
                            if (tranFlg.equals("true")) {
                                for (Receipt receipt1 : receiptList) {
                                    receipt1.setIsSendSccs(1);  // 1--已推送
                                    receiptRepository.save(receipt1);
                                }
                            }
                        }
                    } else if (mtBwart.equals("出库任务取消")) {
                        if (flag == 0) {    // 全部完成
                            /** 更新收货单状态 */
                            for (Receipt receipt1 : receiptList) {
                                receipt1.setStatus("2");  // 2--收货完成
                                receiptRepository.save(receipt1);
                            }
                        }
                    } else if (mtBwart.equals("盘点差异入库")) {
                        if (flag == 0) {    // 全部完成
                            /** 更新收货单状态 */
                            for (Receipt receipt1 : receiptList) {
                                receipt1.setStatus("2");  // 2--收货完成
                                receiptRepository.save(receipt1);
                            }
                        }
                    } else if (mtBwart.equals("411")) {
                        /** 411 */
                        if (flag == 0) {    // 全部完成
                            /** 更新收货单状态 */
                            for (Receipt receipt1 : receiptList) {
                                receipt1.setStatus("2");  // 2--收货完成
                                receiptRepository.save(receipt1);
                            }
                            List<JSONObject> jsonObjectList = new ArrayList<>();
                            for (Receipt receipt1 : receiptList) {
                                List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt1.getId());
                                for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                                    JSONObject jsonObject1 = new JSONObject();
                                    jsonObject1.put("el_no", receipt1.getElNo());
                                    jsonObject1.put("mr_list", receipt1.getMtList());
                                    jsonObject1.put("lot_no", receipt1.getLotNo());
                                    jsonObject1.put("pk_qty", receiptDetail1.getPkQty());
                                    jsonObject1.put("pk_list", receiptDetail1.getPkList());
                                    jsonObject1.put("rtd_user", "admin");
                                    jsonObjectList.add(jsonObject1);
                                }
                            }
                            log.info("411入库，推送给SCCS，" + jsonObjectList);
                            String url = sccsIp + ":" + sccsPort + "/RTDSXWMS/WMSImportPD07";
                            JSONObject jsonObjectSend = new JSONObject();
                            jsonObjectSend.put("Sjson", JSON.toJSONString(jsonObjectList));
                            String resp = commonUtil.httpPost(url, JSON.toJSON(jsonObjectSend));
                            log.info("411入库，SCCS返回，" + resp);
                            String respString = StrUtil.strip(resp, "\"").replaceAll("\\\\", "");
                            JSONObject jsonObjectResp = JSON.parseObject(respString);
                            String tranFlg = jsonObjectResp.getString("tran_flg");
                            if (tranFlg.equals("true")) {
                                for (Receipt receipt1 : receiptList) {
                                    receipt1.setIsSendSccs(1);  // 1--已推送
                                    receiptRepository.save(receipt1);
                                }
                            }
                        }
                    } else if (mtBwart.equals("412")) {
                        /** 412 */
                        if (flag == 0) {    // 全部完成
                            /** 更新收货单状态 */
                            for (Receipt receipt1 : receiptList) {
                                receipt1.setStatus("2");  // 2--收货完成
                                receiptRepository.save(receipt1);
                            }
                            List<JSONObject> jsonObjectList = new ArrayList<>();
                            for (Receipt receipt1 : receiptList) {
                                List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt1.getId());
                                for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                                    JSONObject jsonObject1 = new JSONObject();
                                    jsonObject1.put("el_no", receipt1.getElNo());
                                    jsonObject1.put("mr_list", receipt1.getMtList());
                                    jsonObject1.put("lot_no", receipt1.getLotNo());
                                    jsonObject1.put("pk_qty", receiptDetail1.getPkQty());
                                    jsonObject1.put("pk_list", receiptDetail1.getPkList());
                                    jsonObject1.put("rtd_user", "admin");
                                    jsonObjectList.add(jsonObject1);
                                }
                            }
                            log.info("412入库，推送给SCCS，" + jsonObjectList);
                            String url = sccsIp + ":" + sccsPort + "/RTDSXWMS/WMSImportPD07";
                            JSONObject jsonObjectSend = new JSONObject();
                            jsonObjectSend.put("Sjson", JSON.toJSONString(jsonObjectList));
                            String resp = commonUtil.httpPost(url, JSON.toJSON(jsonObjectSend));
                            log.info("412入库，SCCS返回，" + resp);
                            String respString = StrUtil.strip(resp, "\"").replaceAll("\\\\", "");
                            JSONObject jsonObjectResp = JSON.parseObject(respString);
                            String tranFlg = jsonObjectResp.getString("tran_flg");
                            if (tranFlg.equals("true")) {
                                for (Receipt receipt1 : receiptList) {
                                    receipt1.setIsSendSccs(1);  // 1--已推送
                                    receiptRepository.save(receipt1);
                                }
                            }
                        }
                    }
                } else if (tasks.getTaskType() == 10) {
//                    JSONObject jsonObjects = new JSONObject();
//                    if (stationCode.equals("CY01")) {
//                        jsonObjects.put("slotCode", "1-5");
//                    } else if (stationCode.equals("CY02")) {
//                        jsonObjects.put("slotCode", "2-5");
//                    }
//                    jsonObjects.put("slotCode", stationCode);
//                    jsonObjects.put("containerCode", containerCode);
//                    jsonObjects.put("direction", "200");
//                    String sp = commonUtil.httpPost("http://" + agvIp + ":" + agvPort + "/conveyor/moveContainer", jsonObjects);
                }
                break;
            default:
                break;
        }
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("code", 0);
        jsonObject1.put("msg", "success");
        jsonObject1.put("data", null);

        return new Result(0,"success",new JSONObject());
    }

    @Override
    public String agvCarLeave() {
        String shuSongXian = "";
        if (SecurityUtils.getCurrentUsername().equals("admin")) {
            shuSongXian = "LT_CONVEYOR_OUTPUT:POINT:26965:11110";
        } else if (SecurityUtils.getCurrentUsername().equals("song")) {
            shuSongXian = "LT_CONVEYOR_OUTPUT:POINT:26965:9160";
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("locationCode", shuSongXian);
        jsonObject.put("stationCode", "");
        jsonObject.put("robotCode", "");
        String url = "http://" + agvIp + ":" + agvPort + "/station/letRobotGo";
        System.out.println(JSON.toJSONString(jsonObject));
        String s = commonUtil.httpPost(url, JSON.toJSONString(jsonObject));
        if (s.contains("success")) {
            return "success";
        } else {
            return "fail";
        }
    }

}